package com.jiyinit.web.core.mobile.controller;

import com.jiyinit.core.framework.base.entity.ResponseDto;
import com.jiyinit.web.core.business.entity.TabCorePrcEntity;
import com.jiyinit.web.core.business.enums.CommonEnum;
import com.jiyinit.web.core.business.service.PrctureServiceImpl;
import com.jiyinit.web.core.common.config.PropertyPlaceholderConfigurer;
import com.jiyinit.web.core.common.util.UserUtil;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

/**
 * Created by lr on 2017/12/19.
 */
@Controller
@RequestMapping("/mobile/prc")
public class MprcController {

    /**
     * 日志对象
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(MprcController.class);

    @Resource(name = "core.prcServiceImpl")
    private PrctureServiceImpl prctureServiceImpl;

    /**
     * 图片上传流
     * @param type 1:头像
     * @return
     */
    @ResponseBody
    @RequestMapping(method = RequestMethod.POST, value = "/upload")
    public ResponseEntity<ResponseDto> uploadPrc(HttpServletRequest request,HttpServletResponse response,@RequestParam("myFile") MultipartFile myFile,int type){
        String str = "";
        try {
            DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
            //图片名称
            String name = df.format(new Date());

            Random r = new Random();
            for (int i = 0; i < 3; i++) {
                name += r.nextInt(10);
            }
            String ext = FilenameUtils.getExtension(myFile.getOriginalFilename());
            //保存图片       File位置 （全路径）   /upload/fileName.jpg
            // String url = request.getSession().getServletContext().getRealPath("/upload/img");
            //获取文件的保存路径
            String url = (String) PropertyPlaceholderConfigurer.getContextProperty("PRC_PATH");
            System.out.print("url:" + url);
            //相对路径
            String path = name + "." + ext;
            File file = new File(url);
            if (!file.exists()) {
                file.mkdirs();
            }
            str = url + path;
            myFile.transferTo(new File(str));
        }catch(IOException e){
            return new ResponseEntity<ResponseDto>(ResponseDto.responseFail("文件上传失败"), HttpStatus.OK);
        }
            //保存到图片表中
            TabCorePrcEntity picture = new TabCorePrcEntity();
            picture.setPrcType(type);
            picture.setPrcPath(str);
            picture.setIsDelete(CommonEnum.IsDelete.COMMON.getCode());
            picture.setCreateId(UserUtil.getCurrentUser().getUserId());
            picture.setCreateTime(new Date());

            int num = prctureServiceImpl.insert(picture);
        return new ResponseEntity<ResponseDto>(ResponseDto.responseFail(""), HttpStatus.OK);
    }

    @RequestMapping("/download/{prcId}")
    public void down(@PathVariable("prcId")Integer prcId,HttpServletRequest request,HttpServletResponse response) throws IOException {
        if(prcId == null){
            return ;
        }
        response.setContentType("image/png");
        OutputStream stream = response.getOutputStream();

        TabCorePrcEntity entity = prctureServiceImpl.getById(prcId);
        File file  = new File(entity.getPrcPath());
        InputStream inputStream = new FileInputStream(file);
        byte[] data = new byte[1024];
        int length = inputStream.read(data);
        while(length>0){
            stream.write(data);
            length = inputStream.read(data);
        }
        inputStream.close();
        stream.flush();
        stream.close();
    }
}
